package com.llj.chatbidemo.controller;

import com.alibaba.fastjson.JSON;
import com.llj.chatbidemo.config.ChatAITool;
import com.llj.chatbidemo.config.Result;
import com.llj.chatbidemo.service.ChatBIServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.*;
import java.util.Map;


@RestController
@RequestMapping("/api/chatbi")
@Tag(name = "ChatBI接口", description = "用于数据分析接口")
public class ChatBIController {

    @Autowired
    private ChatBIServiceImpl chatBIService;

    @Autowired
    private ChatAITool chatAITool; // 应能正常注入

    @PostMapping("/ask")
    public String ask(@RequestBody String question) {
        return chatAITool.askQuestion(question);
    }


    // 自然语言转SQL
    @PostMapping("/ask1")
    @CrossOrigin
    public Result askQuestion(@RequestParam("question") String question) {

        //对用户问题进行NLP预处理,目前感觉没太必要
        //String prompt = nlpUtils.preprocessInput(question);

        //得到sql语句
        String sql = chatBIService.naturalLanguageToSQL(question);

        String analysis;
        try {
            //得到分析
            analysis = chatBIService.analyzeData(question, sql);
        } catch (BadSqlGrammarException e) {
            System.out.println("SQL语法错误: " + e.getMessage());
            return Result.error(2, "ai生成的SQL语法错误 sql：" + sql);
        }

        String echartsConfig;
        try {
            //得到echarts配置
            echartsConfig = chatBIService.generateEChartsConfig(sql, question);
        } catch (BadSqlGrammarException e) {
            return Result.error(2, "ai生成图表失败，失败原因" +e.getMessage());
        }

        System.out.println("SQL: " + sql);
        System.out.println(" Analysis: "+analysis);
        System.out.println("EChartsConfig: " + echartsConfig);
        return Result.success(Map.of(
                "success", true,
                "sql", sql,
                "analysis", JSON.parse(analysis) // 按需解析
                , "option", JSON.parse(echartsConfig)
        ));

    }

    // 指标解释服务
    @GetMapping("/explain/{metric}")
    public String explainMetric(@PathVariable String metric) {
        return chatBIService.explainMetric(metric);
    }

}
